package com.jingyanzi.sys.util;



import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class ParamUtils {
	
	public static final String pattern = "yyyy-MM-dd HH:mm";
	public static final String FULL_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String MINUTES_PATTERN = "MM-dd";
	
	public static String uuid32(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	public static String uuid36(){
		return UUID.randomUUID().toString();
	}

	public static String randomIntLength(int length){
		length=length-1;
		int[] arr = {1,2,3,4,5,6,7,8,9,0};
		StringBuilder reStr = new StringBuilder();

		for(int i = 0,size=length; i<size; i++) {
			reStr.append(arr[new Random().nextInt(arr.length)]);
		}

		return reStr.toString();
	}

	public static String valueOf(Object obj){
		if(obj==null)
			return null;
		return String.valueOf(obj);
	}

	/**
	 * 字符串转换为int,如不能转换设置为默认值
	 * @param str
	 * @param defaultValue
     * @return
     */
	public static int parseInt(String str, int defaultValue){
		if(str==null || str.length()==0){
			return defaultValue;
		}
		try{
			return Integer.parseInt(str);
		}catch (Throwable e) {
			return defaultValue;
		}
	}

	/**
	 *
	 * @param obj
	 * @param defaultStr
     * @return
     */
	public static String parseStr(Object obj,String defaultStr){
		if(obj==null||ParamUtils.isEmpty(obj+"")){
			return defaultStr;
		}

		return obj+"";
	}

	/**
	 * 字符串转换为double,如不能转换设置为默认值
	 * @param str
	 * @param defaultValue
     * @return
     */
	public static double parseDouble(String str, double defaultValue){

		if(str==null || str.length()==0){
			return defaultValue;
		}
		try{
			return Double.parseDouble(str);
		}catch (Throwable e) {
			return defaultValue;
		}
	}
	

	
    public static String objectToJsonDateSerializer(Object ts,    
            final String dateformat) {    
        String jsonStr = null;    
        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class,
                        new JsonSerializer<Date>() {    
                            public JsonElement serialize(Date src,    
                                    Type typeOfSrc,    
                                    JsonSerializationContext context) {  
                            	if(ParamUtils.isEmpty(dateformat)){
                            		return new JsonPrimitive(src.getTime());
                            	}else{
                                SimpleDateFormat format = new SimpleDateFormat(    
                                        dateformat);    
                                return new JsonPrimitive(format.format(src)); 
                            	}
                            }    
                        }).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        if (gson != null) {    
            jsonStr = gson.toJson(ts);    
        }    
        return jsonStr;    
    }    

	private ParamUtils(){
		
	}


	public static boolean isEmpty(String name) {
		return name == null || "".equals(name);
	}

	/**
	 * 判断不为空
	 * @param name
	 * @return
     */
	public static boolean isNotEmpty(Object name) {
		return !(name == null || "".equals(name));

	}

	/**
	 * 将url参数转换成map
	 * @param url *.html?aa=11&bb=22&cc=33
	 * @return
	 */
	public static Map<String, Object> getUrlParams(String url) {

		String[] urlArr=url.split("[?]");
		String param = urlArr.length==2?urlArr[1]:"";

		Map<String, Object> map = new HashMap<String, Object>(0);
		if (ParamUtils.isEmpty(param)) {
			return map;
		}
		String[] params = param.split("&");
		for (int i = 0; i < params.length; i++) {
			String[] p = params[i].split("=");
			if (p.length == 2) {
				map.put(p[0], p[1]);
			}
		}
		return map;
	}


	/**
	 * 将url参数转换成map
	 * @param params aa=11&bb=22&cc=33
	 * @return
	 */
	public static String getUrlParams(Map<String, String > params) {
		if(params==null){
			return "";
		}

		List<String> result=new LinkedList<String>();

		Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry<String, String> entry = entries.next();

			result.add(entry.getKey()+"="+entry.getValue());
		}

		return org.apache.commons.lang.StringUtils.join(result.toArray(),"&");
	}

	/**
	 * 解码
	 * @param str
	 * @param enc
     * @return
     */
	public static String getUrlDecode(String str,String enc)
	{
		String reStr ="";
		try {
			reStr =URLDecoder.decode(str, enc);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return reStr;
	}

	/**
	 * 转码
	 * @param str
	 * @param enc
     * @return
     */
	public static String getUrlEncode(String str,String enc){
		String reStr ="";
		try {
			reStr = URLEncoder.encode(str, enc);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return reStr;
	}

	/**
	 *
	 * @param list
	 * @param attr
	 * @param val
	 * @return
	 */
	public static List<Map<String,Object>> listForAttrVal(List<Map<String, Object>> list, String attr, String val){
		List<Map<String,Object>> li = new ArrayList();
		for(int i=0;i<list.size();i++){
			if(val.equals(list.get(i).get(attr))){
				li.add(list.get(i));
			}else if(null == list.get(i).get(attr) && val.equals("")){
				li.add(list.get(i));
			}
		}
		return li;
	}

	public static void main(String[] args) {
//		System.out.println(StringUtils.randomIntLength(10));

		Map<String,String> params = new HashMap<String,String>();
		params.put("openId","sdfsdfsss");





	//	System.out.println(StringUtils.getUrlParams(params));
	}

	public static String getValue(Object obj) {
		if(obj==null){
			return "";
		}

		return obj+"";
	}
}
